const { getReqToken, getDecodeToken } = require("../../utils");

const Service = require("egg").Service;
module.exports = class UserService extends Service {
  /**
   * 查询表格的第一条记录（按id升序排列）
   * @param {string} tableName 表格数据
   * @returns {object[]}
   */
  async getFirstRecord(tableName = "user", mainKey = "id") {
    const sql = `SELECT * FROM ${tableName} ORDER BY ${mainKey} ASC LIMIT 1;`;
    const rows = await this.app.mysql.query(sql);
    return rows;
  }
  // 查用户信息
  async getUserInfo(key) {
    const { ctx, service } = this;
    const token = getReqToken(ctx);
    const { phone } = getDecodeToken(this, token);
    const info = await service.common.detail("user", { where: { phone } });
    if (!key) return info;
    return info[key];
  }
  /**
   * 获取操作信息（含操作人、操作时间）
   * @param {create|update} type 操作类型：创建、修改
   */
  async getOperateInfo(type = "update") {
    if (!["create", "update"].includes(type)) throw new Error(`暂不支持解析此操作类型：${type}`);
    const { service } = this;
    return {
      [`${type}_time`]: "CURRENT_TIMESTAMP",
      [`${type}_id`]: await service.user.getUserInfo("id"),
      // [`${type.slice(0, -1)}or_id`]: await service.user.getUserInfo("id"),
    };
  }
  // 获取用户id
  getUserId() {
    return this.ctx.session.user.id;
  }
};
